package com.xm.controller;

import com.xm.common.ImageCacheService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;

@RestController
@RequestMapping("/images")
public class ImageController {

    @Autowired
    private ImageCacheService imageCacheService;

    @PostMapping("/upload/{imageId}")
    public ResponseEntity<String> uploadImage(@PathVariable String imageId, @RequestParam MultipartFile file) {
        try {
            imageCacheService.cacheImage(imageId, file);
            return ResponseEntity.ok("Image cached successfully");
        } catch (IOException e) {
            return ResponseEntity.status(500).body("Error caching image");
        }
    }


    @GetMapping("/getImage")
    public void displayImage(String imageUrl, HttpServletResponse response) {
        try {
            String base64Image = imageCacheService.getCachedImage(imageUrl);
            byte[] imageBytes = Base64.getDecoder().decode(base64Image);

            // 设置响应类型为JPEG
            response.setContentType("image/jpeg");
            response.setContentLength(imageBytes.length);
            response.getOutputStream().write(imageBytes);
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new RuntimeException("error get Image");
        }
    }
}
